package me.pplay.playtalk.util.fileUtil;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import me.pplay.playtalk.bean.ChattingRecord;
import me.pplay.playtalk.data.Globals;
import me.pplay.playtalk.util.LogManager;
import me.pplay.playtalk.util.MD5;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

public class ChattingRecordFile {
	
	public static void deleteChattingRecordFile(int skyid){
		String filePath = Globals.FILE_PATH_CACHE_FILE + MD5.toMD5(Globals.skyid +"" + skyid);
		FileUtil.delete(filePath);
	}
	

	public static void saveChattingRecodToFile(ChattingRecord chat, int skyid){
		try {
			String nextLine = "";
			String filePath = Globals.FILE_PATH_CACHE_FILE + MD5.toMD5(Globals.skyid +"" + skyid);
			LogManager.LogShow("ChattingRecordFile", "save chat filePath"+filePath);
			File file = new File(filePath);
			if(!file.exists()){
				try {
					file.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}else{
				nextLine = System.getProperty("line.separator");
			}
			JSONObject array		= getJsonArrayByListChattingRecord(chat);
//			 //true 表示追加写入filePath
//			FileWriter fileWriter = new FileWriter(filePath,true);
//			  //换行写入
//			
//			fileWriter.write(nextLine + array.toString());
			Writer fileWriter = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(file, true),"UTF-8"));
			fileWriter.write(nextLine + array.toString());
			fileWriter.flush();
			fileWriter.close();
			
			// 打开一个随机访问文件流，按读写方式   
//            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");   
//            // 文件长度，字节数   
//            long fileLength = randomFile.length();   
//            // 将写文件指针移到文件尾。   
//            randomFile.seek(fileLength);   
//            randomFile.writeBytes(content);   
//            randomFile.close();   

		} catch (IOException e) {
			e.printStackTrace();
		}catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
//	public static List<ChattingRecord> getChattingRecordByFile(int skyid){
//		
//		List<ChattingRecord> chatList = new ArrayList<ChattingRecord>();;
//		String filePath = Globals.FILE_PATH_CACHE_FILE + MD5.toMD5(Globals.skyid +""+skyid);
//		File file = new File(filePath);
//		if (!file.exists())
//			return chatList;
//		BufferedReader buffer = null;
//		try {
//			InputStreamReader reader	= new InputStreamReader(new FileInputStream(file), "utf-8");
//			buffer 						= new BufferedReader(reader);
//			String tempStr = null;
//			while ((tempStr = buffer.readLine()) != null) {
//				tempStr = tempStr.trim();
//				if(!tempStr.equals("")){
//					System.out.println("json::"+tempStr);
//					JSONTokener jsonParser = new JSONTokener(tempStr);  
//					JSONObject obj 			= (JSONObject)jsonParser.nextValue();//new JSONObject(tempStr);
//					ChattingRecord	record	= new ChattingRecord();
//					if(obj.has("skyid"))
//						record.skyid 		= obj.getInt("skyid");
//					if(obj.has("name"))
//						record.name 		= obj.getString("name");
//					if(obj.has("icon"))
//						record.icon 		= obj.getString("icon");
//					if(obj.has("type"))
//						record.type 		= obj.getString("type");
//					if(obj.has("content"))
//						record.content 		= obj.getString("content");
//					if(obj.has("time"))
//						record.time 		= obj.getString("time");
////					ChattingRecord	record	= new ChattingRecord(obj.getInt("skyid"), obj.getString("name"), 
////							obj.getString("icon"), obj.getString("type"), obj.getString("content"), obj.getString("time"));
//					chatList.add(record);
//				}
//			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		}catch (JSONException e) {
//			e.printStackTrace();
//		}
//		return chatList;
//	}
	
private static JSONObject getJsonArrayByListChattingRecord(ChattingRecord chat) throws JSONException{
	JSONObject obj 	= new JSONObject();
	obj.put("skyid", chat.skyid);
	obj.put("name", chat.name);
	obj.put("icon", chat.icon);
	obj.put("type", chat.type);
	obj.put("content", chat.content);
	obj.put("time", chat.time);
	obj.put("filelength", chat.filelength);
	obj.put("fname", chat.fname);
	obj.put("fpath", chat.fpath);
	obj.put("server_id", chat.server_id);
	return obj;
}

/**
 * @param skyid
 * @param totalCount每次取多少条记录
 * @return
 */
public static List<ChattingRecord> getChattingRecordByFile(int skyid, int totalCount){
		
		List<ChattingRecord> chatList = new ArrayList<ChattingRecord>();;
		String filePath = Globals.FILE_PATH_CACHE_FILE + MD5.toMD5(Globals.skyid +""+skyid);
		LogManager.LogShow("ChattingRecordFile", "getChat filePath"+filePath);
		File file = new File(filePath);
		if (!file.exists())
			return chatList;
		RandomAccessFile raf = null;
		try {
			raf			= new RandomAccessFile(file, "r");
			long len	= raf.length();
			int count	= 1;
			if(len != 0){
				long pos = len - 1;
				while(pos > 0){
					pos--;
					raf.seek(pos);
//					System.out.println("eeeeeeeeeee readByte:"+ raf.readByte());
					if(raf.readByte() == '\n' || pos == 0){
//						if(pos == -1){
//							byte[] bytes = new byte[(int)(len - pos)];
//						}
//							pos = 0;
//						if(pos == 0)
//							pos = -1;
						if(count > totalCount){
							break;
						}
						count ++;
						byte[] bytes = new byte[(int)(len - pos)];
						raf.read(bytes);
						String tempStr = new String(bytes).trim();
						if(tempStr != null && !tempStr.equals("")){
							if(pos == 0 && tempStr.indexOf("{") != 0){
								tempStr = "{" + tempStr;
							}
							System.out.println("json::"+tempStr);
							JSONTokener jsonParser = new JSONTokener(tempStr);  
							JSONObject obj 			= (JSONObject)jsonParser.nextValue();//new JSONObject(tempStr);
							ChattingRecord	record	= new ChattingRecord();
							if(obj.has("skyid"))
								record.skyid 		= obj.getInt("skyid");
							if(obj.has("name"))
								record.name 		= obj.getString("name");
							if(obj.has("icon"))
								record.icon 		= obj.getString("icon");
							if(obj.has("type"))
								record.type 		= obj.getString("type");
							if(obj.has("content"))
								record.content 		= obj.getString("content");
							if(obj.has("time"))
								record.time 		= obj.getString("time");
							if(obj.has("filelength"))
								record.filelength 	= obj.getInt("filelength");
							if(obj.has("fname"))
								record.fname 		= obj.getString("fname");
							if(obj.has("fpath"))
								record.fpath 		= obj.getString("fpath");
							if(obj.has("server_id"))
								record.server_id 	= obj.getInt("server_id");
							
							chatList.add(0, record);
						}
					}
				}
			}
				
		} catch (IOException e) {
			e.printStackTrace();
		}catch (JSONException e) {
			e.printStackTrace();
		}catch (Exception e) {
			e.printStackTrace();
		}
		return chatList;
	}
	
	
}
